package com.saris.primego.service.impl;

import com.saris.primego.common.constant.MessageConstant;
import com.saris.primego.common.constant.StatusConstant;
import com.saris.primego.common.context.BaseContext;
import com.saris.primego.common.exception.DeletionNotAllowedException;
import com.saris.primego.common.exception.EntityNotFoundException;
import com.saris.primego.common.result.PageResult;
import com.saris.primego.dao.DishFlavorRepository;
import com.saris.primego.dao.DishRepository;
import com.saris.primego.dao.SetmealDishRepository;
import com.saris.primego.pojo.dto.DishDTO;
import com.saris.primego.pojo.dto.DishPageQueryDTO;
import com.saris.primego.pojo.entity.Dish;
import com.saris.primego.pojo.entity.DishFlavor;
import com.saris.primego.pojo.vo.DishVO;
import com.saris.primego.service.DishService;
import jakarta.persistence.criteria.Predicate;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.webjars.NotFoundException;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    private final ModelMapper modelMapper;
    private final DishRepository dishRepository;
    private final DishFlavorRepository dishFlavorRepository;
    private final SetmealDishRepository setmealDishRepository;


    public DishServiceImpl(ModelMapper modelMapper, DishRepository dishRepository, DishFlavorRepository dishFlavorRepository, SetmealDishRepository setmealDishRepository) {
        this.dishRepository = dishRepository;
        this.modelMapper = modelMapper;
        this.dishFlavorRepository = dishFlavorRepository;
        this.setmealDishRepository = setmealDishRepository;
    }

    /**
     * 新增菜品及对应的口味
     */
    @Override
    @Transactional
    public void addDishWithFlavor(DishDTO dto) {
        Dish dish = modelMapper.map(dto, Dish.class);

        // 向菜品表插入一条数据
        Long id = dishRepository.saveAndFlush(dish).getId();

        // 向口味表插入N条数据
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            for (DishFlavor f : flavors) {
                f.setDishId(id);
                dishFlavorRepository.saveAndFlush(f);
            }
        }
    }


    /**
     * 菜品分页查询
     */
    @Override
    public PageResult<DishVO> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        int size = dishPageQueryDTO.getPageSize();
        int page = dishPageQueryDTO.getPage();
        String name = dishPageQueryDTO.getName();
        Integer categoryId = dishPageQueryDTO.getCategoryId();
        Integer status = dishPageQueryDTO.getStatus();

        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("id").descending());

        // 动态构建查询条件
        Specification<Dish> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 当 name 不为空时，添加 name 条件
            if (name != null && !name.trim().isEmpty()) {
                predicates.add(cb.like(root.get("name"), "%" + name + "%"));
            }
            // 当 categoryId 不为空时，添加 categoryId 条件
            if (categoryId != null) {
                predicates.add(cb.equal(root.get("categoryId"), categoryId));
            }
            // 当 status 不为空时，添加 status 条件
            if (status != null) {
                predicates.add(cb.equal(root.get("status"), status));
            }
            if (predicates.isEmpty()) {
                return cb.conjunction();

            } else {
                return cb.and(predicates.toArray(new Predicate[0]));
            }

        };

        Page<Dish> all = dishRepository.findAll(spec, pageable);
        long totalElements = all.getTotalElements();
        List<Dish> content = all.getContent();

        // 映射到 List<DishVo>（解决泛型擦除问题）
        List<DishVO> dishVOS = modelMapper.map(content, new TypeToken<List<DishVO>>() {
        }.getType());

        return new PageResult<>(totalElements, dishVOS);
    }

    /**
     * 菜品批量删除
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            //判断当前菜品是否能够删除---是否存在启售中的菜品？
            dishRepository.findById(id).ifPresent(dish -> {
                if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE))
                    throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            });

            //判断当前菜品是否能够删除---是否被套餐关联？
            if (!setmealDishRepository.findSetmealDishByDishId(id).isEmpty())
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

            //删除菜品中的菜品数据
            dishRepository.deleteById(id);

            //删除菜品关联的口味数据
            dishFlavorRepository.deleteDishFlavorsByDishId(id);
        }

    }

    /**
     * 根据id查询菜品和对应的口味数据
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //查询菜品
        return dishRepository.findById(id)
                .map(dish -> {
                    DishVO dishVO;
                    dishVO = modelMapper.map(dish, DishVO.class);
                    //查询对应口味
                    List<DishFlavor> dishFlavors = dishFlavorRepository.getAllByDishId(id);

                    //组合DVO
                    dishVO.setFlavors(dishFlavors);
                    return dishVO;
                }).orElseThrow(() -> new EntityNotFoundException(MessageConstant.DISH_NOT_FOUND));
    }


    /**
     * 根据id修改菜品基本信息和对应的口味信息
     */
    @Transactional
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {

        //删除原有的口味数据
        dishFlavorRepository.deleteAllByDishId(dishDTO.getId());
        dishFlavorRepository.flush();// 强制刷新，确保删除操作提交

        // 3. 插入新的口味数据（关键：重置所有id为null）
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            // 使用Stream确保每个对象都被处理
            List<DishFlavor> newFlavors = flavors.stream()
                    .peek(flavor -> {
                        flavor.setDishId(dishDTO.getId());
                        flavor.setId(null); // 强制重置ID为null
                    })
                    .collect(Collectors.toList());

            dishFlavorRepository.saveAll(newFlavors); // 批量保存
        }


        //修改菜品表基本信息
        Dish dish = modelMapper.map(dishDTO, Dish.class);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishRepository.saveAndFlush(dish);

    }

    /**
     * 菜品起售停售
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = dishRepository.findById(id).orElseThrow(() -> new NotFoundException(MessageConstant.DISH_NOT_FOUND));

        if (dish.getStatus().equals(StatusConstant.ENABLE)) {
            dish.setStatus(StatusConstant.DISABLE);
        } else {
            dish.setStatus(StatusConstant.ENABLE);
        }

        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());

        dishRepository.save(dish);


    }

    /**
     * 条件查询菜品和口味
     */
    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        List<DishVO> list = new ArrayList<>();
        List<Dish> dishes = dishRepository.findAllByCategoryIdAndStatus(categoryId, StatusConstant.ENABLE);
        if (dishes != null && !dishes.isEmpty()) {
            for (Dish dish : dishes) {
                List<DishFlavor> dishFlavors = dishFlavorRepository.getAllByDishId(dish.getId());
                DishVO dishVO = modelMapper.map(dish, DishVO.class);
                dishVO.setFlavors(dishFlavors);
                list.add(dishVO);
            }
        }
        return list;
    }

    /**
     * 根据菜品Id获得分类Id
     */
    @Override
    public Long getCategoryId(Long id) {
        Dish dish = dishRepository.findById(id).orElseThrow(()->new EntityNotFoundException(MessageConstant.DISH_NOT_FOUND));
        return dish.getCategoryId();
    }

    /**
     * 根据分类id查询菜品
     */
    @Override
    public List<Dish> list(Long categoryId) {
        return dishRepository.findAllByCategoryIdAndStatus(categoryId, StatusConstant.ENABLE);
    }
}
